import {createStore} from 'redux'
import {CarProductInter} from '../types/product'

interface Istate{
    list:CarProductInter[],
    checkAll:boolean
}

//获取index
function getIndex(data:CarProductInter[],id:number){
    return data.findIndex(item => item.id === id)
}

let reducer = (state:Istate={list:[],checkAll:true},action:any) => {
    switch (action.type) {
        case 'ADD_CAR':{
            //action.target
            let {target} = action;
            let index = getIndex(state.list,target.id);
            if(index === -1){
                //第一次添加
                 target.num = 1;    //购买的数量
                 target.checked = true; //选中状态
                 state.list = [...state.list,target];
            }else{
                //不是第一次添加
                console.log("=====不是第一次添加")
                let carProduct = state.list[index];
                carProduct.num++;
            }
            state.checkAll = state.list.every(item => item.checked);
            return {...state,list:[...state.list]};
        }
        // 改变数量
        case 'CHANGE_NUM':{
            // action.id  action.num :修改之后的数量
            let index = getIndex(state.list,action.id);

            let target = state.list[index];
            target.num = action.num;

            console.log(target.num);
            
            state.list[index] = {...target};

            return {...state,list:[...state.list]}
        }
        //删除
        case 'DEL_PRODUCT':{
            //action.id
            let index = getIndex(state.list,action.id);
            state.list.splice(index,1);
            return {...state,list:[...state.list]}
        }

        //改变选中和不选中
        case 'CHANGE_CHECKED':{
            //action.id 要改变的状态的对象id action.checked 改变之后的状态
            let index = getIndex(state.list,action.id);
            let target = state.list[index];
            console.log(action.checked)
            target.checked = action.checked;
            state.list[index] = {...target};
            //重置全选的状态
            state.checkAll = state.list.every(item => item.checked);
            return {...state,list:[...state.list]}
        }

        //全选
        case 'CHEAK_ALL':{
            //action.checked  全选的状态  

            state.list = state.list.map(item => {
                item.checked = action.checked;
                return {...item};
            })
            state.checkAll = action.checked;
            return {...state,list:[...state.list]}
        }
        default:
            return state;
    }
}

let store = createStore(reducer)

export default store